package cn.lyvust.demo.shili12;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Description: 演示ArrayList线程不安全
 * date: 2021-5-18 8:09
 *
 * @author Guo_guo
 * @since JDK 1.8
 */
public class ArrayListUnSafe {
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        final List<Integer> list = new ArrayList<Integer>();
        // vector 线程安全
//        final Vector<Integer> list = new Vector<>();

        // 线程A将0-1000添加到list
        Thread t = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 1000 ; i++) {
                    list.add(i);

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
//        t.join();

        // 线程B将1000-2000添加到列表
        Thread task = new Thread(() -> {
                for (int i = 1000; i < 2000 ; i++) {
                    list.add(i);

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        });
        task.start();
//        task.join();

        // 让主线程等待3秒，确保两个子线程都能执行完成
        Thread.sleep(3000);

        // 打印所有结果
        System.out.println("ArrayList的元素个数:" + list.size());
        for (int i = 0; i < list.size(); i++) {
            System.out.println("第" + (i + 1) + "个元素为：" + list.get(i));
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("程序执行花费的总时间:" + totalTime);
    }
}
